package com.yin.waimai.controller;

import com.yin.waimai.dto.AddressDTO;
import com.yin.waimai.service.AddressCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/v1/addresses")
public class AddressController {

    @Autowired
    private AddressCacheService addressCacheService;

    /**
     * 获取当前用户的所有常用地址
     */
    @GetMapping("/me")
    public ResponseEntity<List<AddressDTO>> getUserAddresses() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userId = auth.getName();
        List<AddressDTO> addresses = addressCacheService.getUserAddresses(userId);
        return ResponseEntity.ok(addresses);
    }

    /**
     * 保存用户的常用地址
     */
    @PostMapping("/me")
    public ResponseEntity<AddressDTO> saveUserAddress(@Valid @RequestBody AddressDTO addressDTO) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userId = auth.getName();
        addressCacheService.saveUserAddress(userId, addressDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(addressDTO);
    }

    /**
     * 更新用户的某个常用地址
     */
    @PutMapping("/me/{addressId}")
    public ResponseEntity<AddressDTO> updateUserAddress(@PathVariable String addressId, @Valid @RequestBody AddressDTO addressDTO) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userId = auth.getName();
        
        // 设置地址ID
        addressDTO.setId(addressId);
        
        // 保存更新后的地址
        addressCacheService.saveUserAddress(userId, addressDTO);
        
        return ResponseEntity.ok(addressDTO);
    }

    /**
     * 删除用户的某个常用地址
     */
    @DeleteMapping("/me/{addressId}")
    public ResponseEntity<Void> deleteUserAddress(@PathVariable String addressId) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String userId = auth.getName();
        boolean deleted = addressCacheService.deleteUserAddress(userId, addressId);
        
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}